from django import forms
from django.contrib.auth import login
from django.contrib.auth.models import User

from . import constants, models


class LoginForm(forms.Form):
    """登录校验"""
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super().__init__(*args, **kwargs)

    username = forms.CharField(
        label="用户名",
        error_messages={
            "required": "用户名或密码不能为空",
        }
    )

    password = forms.CharField(
        label="密码",
        error_messages={
            "required": "用户名或密码不能为空",
        }
    )

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")

        # 找到用户
        user_queryset = User.objects.filter(username=username)
        # 密码校验
        if user_queryset:
            user = user_queryset.first()
            if user.check_password(password):
                self.request.session.set_expiry(constants.DEFAULT_LOGIN_TIME * 24 * 3600)
                login(self.request, user)
            else:
                raise forms.ValidationError("用户名或密码错误")
        else:
            raise forms.ValidationError("用户名或密码错误")

        return cleaned_data
